<template>
  <Modal id="register"
         v-model="visible"
         width="600px"
         okText="确认"
         title="用户注册"
         @on-ok="handleSubmit">
    <Form class="clearfix formCustom"
          ref="formCustom"
          :model="formCustom"
          :rules="ruleCustom"
          :label-width="80">
      <FormItem label="昵称"
                prop="loginName">
        <Input v-model="formCustom.loginName"
               placeholder="设置登录用户名"></Input>
      </FormItem>
      <FormItem label="真实姓名"
                prop="name">
        <Input v-model="formCustom.name"
               placeholder="真实姓名"></Input>
      </FormItem>
      <FormItem label="密码"
                prop="passwd">
        <Input type="password"
               v-model="formCustom.passwd"
               placeholder="设置登录密码"></Input>
      </FormItem>
      <FormItem label="确认密码"
                prop="passwdCheck">
        <Input type="password"
               v-model="formCustom.passwdCheck"></Input>
      </FormItem>
      <FormItem label="角色"
                prop="role">
        <Select v-model="formCustom.role"
                style="width:200px">
          <Option v-for="item in options"
                  :value="item.value"
                  :key="item.value">{{ item.label }}</Option>
        </Select>
      </FormItem>
      <FormItem v-if="formCustom.role==='3'"
                label="班级"
                prop="classes">
        <div>格式：18级XX系02班</div>
        <Input v-model="formCustom.classes"
               placeholder="按照上面格式填写"></Input>
      </FormItem>
      <FormItem label="联系电话"
                prop="tel">
        <Input v-model="formCustom.tel"></Input>
      </FormItem>
      <FormItem class="clearfix"
                label="联系邮箱"
                prop="mail">
        <Input v-model="formCustom.mail"></Input>
      </FormItem>

    </Form>
    <div>头像上传</div>
    <div class="demo-upload-list"
         v-if="this.uploadList.length">
      <template>
        <img :src="avatarUrl">
        <div class="demo-upload-list-cover">
          <Icon type="ios-eye-outline"
                @click.native="handleView()"></Icon>
          <Icon type="ios-trash-outline"
                @click.native="handleRemove()"></Icon>
        </div>
      </template>
    </div>
    <Upload ref="upload"
            :show-upload-list="false"
            :default-file-list="defaultList"
            :on-success="handleSuccess"
            :format="['jpg','jpeg','png']"
            :max-size="2048"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :before-upload="handleBeforeUpload"
            type="drag"
            action="//jsonplaceholder.typicode.com/posts/"
            style="display: inline-block;width:58px;">
      <div style="width: 58px;height:58px;line-height: 58px;">
        <Icon type="ios-camera"
              size="20"></Icon>
      </div>
    </Upload>
    <Modal title="View Image"
           v-model="visible2">
      <img :src="avatarUrl"
           v-if="visible2"
           style="width: 100%">
    </Modal>
    <div slot="footer"
         class="footer">
      <Button type="primary"
              @click="visible=false">取消</Button>
      <Button type="primary"
              @click="handleSubmit">确认</Button>
    </div>
  </Modal>
</template>
<script>
import { addUser } from '@/api/user'
export default {
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.formCustom.passwdCheck !== '') {
          // 对第二个密码框单独验证
          this.$refs.formCustom.validateField('passwdCheck')
        }
        callback()
      }
    }
    const validatePassCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请确认密码'))
      } else if (value !== this.formCustom.passwd) {
        callback(new Error('两次密码输入不一致!'))
      } else {
        callback()
      }
    }
    const telCheck = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else {
        if (!/^1[34578]\d{9}$/.test(value)) {
          callback(new Error('请输入正确的电话号码'))
        } else {
          callback()
        }
      }
    }
    const classesCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请按照示例格式输入班级'))
      } else {
        // /^1[34578]\d{9}$/
        if (!/^\d{2}级\S*系\d{2}班$/.test(value)) {
          callback(new Error('输入格式有误'))
        } else {
          callback()
        }
      }
    }

    return {
      visible: false,
      avatarUrl: '',
      formCustom: {
        loginName: '',
        name: '',
        role: '',
        classes: '',
        tel: '',
        mail: '',
        passwd: '',
        passwdCheck: ''
      },
      ruleCustom: {
        passwd: [{ validator: validatePass, trigger: 'blur' }],
        passwdCheck: [{ validator: validatePassCheck, trigger: 'blur' }],
        name: [
          {
            required: true,
            message: '请填写真实姓名',
            trigger: 'blur'
          }
        ],
        loginName: [
          {
            required: true,
            message: '请填写昵称',
            trigger: 'blur'
          }
        ],
        role: [
          {
            required: true,
            message: '请选择角色',
            trigger: 'blur'
          }
        ],
        classes: [{ validator: classesCheck, trigger: 'blur' }],
        mail: [{ type: 'email', message: '邮箱格式错误', trigger: 'blur' }],
        tel: [{ validator: telCheck, trigger: 'blur' }]
      },
      loading: false,
      options: [
        {
          value: '3',
          label: '学生'
        },
        {
          value: '2',
          label: '老师'
        },
        {
          value: '4',
          label: '专家'
        }
      ],
      defaultList: [
        {
          name: 'a42bdcc1178e62b4694c830f028db5c0',
          url:
            'https://o5wwk8baw.qnssl.com/a42bdcc1178e62b4694c830f028db5c0/avatar'
        },
        {
          name: 'bc7521e033abdd1e92222d733590f104',
          url:
            'https://o5wwk8baw.qnssl.com/bc7521e033abdd1e92222d733590f104/avatar'
        }
      ],
      imgName: '',
      visible2: false,
      uploadList: []
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.uploadList = []
        this.avatarUrl = ''
        this.$refs.formCustom.resetFields()
      })
    },
    handleSubmit () {
      let data = new FormData()
      let key = Object.keys(this.formCustom)
      key.forEach(element => {
        if (this.formCustom[element] !== '' && element !== 'passwdCheck') {
          data.append(element, this.formCustom[element])
        }
      })
      data.append('avatar', this.uploadList[0])
      this.$refs['formCustom'].validate(valid => {
        if (valid) {
          addUser(data).then(() => {
            this.$Message.success('Success!')
            this.visible = false
          })
        }
      })
    },
    handleView (name) {
      this.imgName = name
      this.visible2 = true
    },
    handleRemove () {
      this.uploadList = []
      this.avatarUrl = ''
    },
    handleSuccess (res, file) {
      file.url =
        'https://o5wwk8baw.qnssl.com/7eb99afb9d5f317c912f08b5212fd69a/avatar'
      file.name = '7eb99afb9d5f317c912f08b5212fd69a'
    },
    handleFormatError (file) {
      this.$Notice.warning({
        title: 'The file format is incorrect',
        desc:
          'File format of ' +
          file.name +
          ' is incorrect, please select jpg or png.'
      })
    },
    handleMaxSize (file) {
      this.$Notice.warning({
        title: 'Exceeding file size limit',
        desc: 'File  ' + file.name + ' is too large, no more than 2M.'
      })
    },
    handleBeforeUpload (file) {
      if (
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg'
      ) {
        let reader = new FileReader()
        reader.readAsDataURL(file)
        const _this = this
        reader.onloadend = function (e) {
          _this.avatarUrl = reader.result
          _this.uploadList = [file]
        }
      } else {
        this.$Message.error('请选择格式为png、jpg、jpeg的图片')
      }

      return false
    }
  },
  mounted () {
    // this.uploadList = this.$refs.upload.fileList;
  }
}
</script>
<style lang="scss">
#register {
  .formCustom {
    .ivu-form-item {
      width: 50%;
      float: left;
      .ivu-input {
        width: 200px;
      }
    }
  }

  .demo-upload-list {
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    margin-right: 4px;
  }
  .demo-upload-list img {
    width: 100%;
    height: 100%;
  }
  .demo-upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.6);
  }
  .demo-upload-list:hover .demo-upload-list-cover {
    display: block;
  }
  .demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
  .footer {
    text-align: right;
  }
}
</style>


